#!/usr/env/bin python
# -*- coding: utf-8 -*-

# @Time    : 2020-10-29 8:51 上午
# @Author  : yangdy
# @File    : 2020-10-29.129.求根到叶子节点数字之和
# @Software: PyCharmCE
from tools.my_methods import *


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def sumNumbers(self, root: TreeNode) -> int:
        def dfs(rt, val=0):
            if not rt:
                return val
            v = val * 10 + rt.val
            left = dfs(rt.left, v) if rt.left else 0
            right = dfs(rt.right, v) if rt.right else 0
            return left + right if left > 0 or right > 0 else v

        return dfs(root)
